/**
 * Created by felix on 2016/11/02.
 * input tip => IT
 */
import React from 'react';
export default class IT extends React.Component {
    static style = {
        w: {
            position: 'absolute',
            width: '100%',
            maxHeight: '200px',
            overflowY: 'auto',
            zIndex: 13
        },
        l: {
            border: '1px solid #eee',
            backgroundColor: '#fff'
        }
    };
    state = {
        show: this.props.show,
        data: this.props.data || [],
        forId: this.props.forId
    };

    componentWillReceiveProps(np) {
        this.setState({
            show: np.show,
            data: np.data || []
        });
    }

    tipClick(e) {
        const id = this.state.forId;
        if (typeof this.props.tipClick === 'function') {
            this.props.tipClick(id, e.target.innerHTML);
        }
    }

    renderItems(itemsData) {
        const id = this.state.forId;
        if (itemsData && itemsData.length > 0) {
            return itemsData.map((item, i) => {
                const space = /^\s+ | \s+$/,
                    _item = item.toString().replace(space, '');
                if (_item !== '') {
                    return (
                        <li
                            key={`${id}_${i}`}
                            className="tipItem"
                        >
                            {_item}
                        </li>
                    );
                }
                return '';
            });
        }
        return false;
    }

    render() {
        const show = this.state.show ? 'block' : 'none',
            items = this.renderItems(this.state.data);
        return (
            <div
                style={{
                    ...IT.style.w
                }}
                onClick={this.tipClick.bind(this)}
            >
                {items ? (
                    <ul
                        style={{
                            ...IT.style.l,
                            display: show
                        }}
                    >
                        {this.renderItems(this.state.data)}
                    </ul>
                ) : (<span />)}
            </div>
        );
    }
}
